<?php

namespace app\common\model;

use app\common\model\user\Dividendlog;
use app\common\model\user\Level;
use fast\Http;
use think\Db;
use think\Env;
use think\Exception;
use think\Log;
use think\Model;

/**
 * 会员模型
 */
class User extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'url',
    ];


    public function userlevel()
    {
        return $this->belongsTo('app\common\model\user\Level', 'level_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    /**
     * 获取个人URL
     * @param string $value
     * @param array  $data
     * @return string
     */
    public function getUrlAttr($value, $data)
    {
        return "/u/" . $data['id'];
    }

    /**
     * 获取头像
     * @param string $value
     * @param array  $data
     * @return string
     */
    public function getAvatarAttr($value, $data)
    {
        if (!$value) {
            //如果不需要启用首字母头像，请使用
            $value = '/assets/img/avatar.png';
            // $value = letter_avatar($data['nickname']);
        }
        return $value;
    }

    /**
     * 获取会员的组别
     */
    public function getGroupAttr($value, $data)
    {
        return UserGroup::get($data['group_id']);
    }

    /**
     * 获取验证字段数组值
     * @param string $value
     * @param array  $data
     * @return  object
     */
    public function getVerificationAttr($value, $data)
    {
        $value = array_filter((array)json_decode($value, true));
        $value = array_merge(['email' => 0, 'mobile' => 0], $value);
        return (object)$value;
    }

    /**
     * 设置验证字段
     * @param mixed $value
     * @return string
     */
    public function setVerificationAttr($value)
    {
        $value = is_object($value) || is_array($value) ? json_encode($value) : $value;
        return $value;
    }

    /**
     * 变更会员余额
     * @param int    $money   余额
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function money($money, $user_id, $memo, $ext = [], $addflag = true)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $money != 0) {
                $before = $user->money;

                //$after = $user->money + $money;
                $after = function_exists('bcadd') ? bcadd($user->money, $money, 2) : $user->money + $money;
                $ud = ['money' => $after];
                if ($money > 0 && $addflag) {
                    $ud['total_money'] = $user->total_money + $money;
                }
                //更新会员信息
                if (array_key_exists('class', $ext) && $ext['class'] == 'week_dividend') {
                    $ud['total_dividend_commission'] = $user->total_dividend_commission + $money;
                }
                $user->save($ud);
                //写入日志
                $data = array_merge($ext, ['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo]);
                $log = new MoneyLog;
                $log->allowField(true)->save($data);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 变更会员积分
     * @param int    $score   积分
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function score($score, $user_id, $memo, $addflag = true)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $score != 0) {
                $before = $user->score;
                $after = $user->score + $score;
                // $level = self::nextlevel($after);
                //更新会员信息
                $ud  = ['score' => $after];
                if ($score > 0 && $addflag) {
                    $ud['total_score'] = $user->total_score + $score;
                }
                $user->save($ud);
                //写入日志
                ScoreLog::create(['user_id' => $user_id, 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 变更会员分红值
     * @param int    $score   分红值
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function dividend($score, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $score != 0 && $user->level_id) {
                $before = $user->dividend;
                $after = $user->dividend + $score;
                // $level = self::nextlevel($after);
                //更新会员信息
                $user->save(['dividend' => $after]);
                //写入日志
                Dividendlog::create(['user_id' => $user_id, 'score' => $score, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 根据积分获取等级
     * @param int $score 积分
     * @return int
     */
    public static function nextlevel($score = 0)
    {
        $lv = array(1 => 0, 2 => 30, 3 => 100, 4 => 500, 5 => 1000, 6 => 2000, 7 => 3000, 8 => 5000, 9 => 8000, 10 => 10000);
        $level = 1;
        foreach ($lv as $key => $value) {
            if ($score >= $value) {
                $level = $key;
            }
        }
        return $level;
    }

    protected static function init()
    {
        self::beforeUpdate(function ($row) {

            $changed = $row->getChangedData();
            if (array_key_exists('level_id', $changed) && $row->level_id) {
                if ($row->pid) {
                    User::where('id', $row->pid)->inc('today_share_vip', 1)->update();
                }
                // if($row->level_id>=4){
                //     $row->level4_sq = User::max('level4_sq')+1;
                // }
                // $ids = $row->team_tag;
                // $ids = explode(',', $ids);
                // if (count($ids) > 1) {
                //     array_pop($ids);
                // }
            }

            // if(array_key_exists('pid', $changed)){

            // }
        });
        self::afterInsert(function ($row) {
            if ($row->pid) {
                $u = self::find($row->id);
                $ids = explode(',', $u->team_tag);
                array_pop($ids);
                self::where('id', 'in', $ids)->inc('team_num', 1)->update();

                foreach ($ids as $id) {
                    $us = self::get($id);
                    if ($us && $us->level_id < 5) {
                        Level::checkUP($us);
                    }
                }
                // var_dump($u->pid);
                // $sql = "update fa_user set team_num=(select count(*) from )"
            }
        });
    }

    /**
     * 创建更新用户
     */
    public static function followuser($openid, $userinfo, $pid = 0)
    {
        //账号注册时需要开启事务,避免出现垃圾数据
        Db::startTrans();
        try {
            $user = self::get(array("openid" => $openid));

            if (!$user) {
                $phone = $userinfo['mobile'] ?? '';
                $data = array(
                    "username" => $userinfo['nickName'] ?? '微信用户',
                    "openid" => $openid,
                    "mobile" => $phone,
                    "unionid" => '',
                    "pid" => $pid,
                    // "nickname" => $userinfo['nickName'] ?? '微信用户',
                    'nickname' => $userinfo['nickName']??($phone ? substr_replace($phone, '****', 3, 4) : '微信用户'),
                    "avatar" => $userinfo['avatarUrl'] ?? '',
                    "status" => 'normal',
                    "group_id" => 1,
                    'jointime' => time()
                );

                $user = new self($data);
                $user->save();
                // self::getQrcode($user);
            } else {
                if ($pid && !$user->pid) {
                    $puser = self::get($pid);
                    if ($puser && $puser->pid != $user->id) {
                        $user->pid = $pid;
                       
                    }
                }
                if($userinfo['nickName']??false){
                    $user->nickname = $userinfo['nickName'];
                }

                if($userinfo['avatarUrl']??false){
                    $user->avatar = $userinfo['avatarUrl'];
                }
                $user->save();
                // $user->username = $user->username ? $user->username : $userinfo['nickName'];
                // $user->openid = $openid;
                // $user->unionid = '';
                // $user->nickname = $userinfo['nickName'];
                // $user->avatar = $userinfo['avatarUrl'];
                // $user->save();
                // self::getQrcode($user);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return false;
        }
        return $user;
    }


    //获取个人分享二维码
    static function getQrcode($user, $path = null, $scene = null)
    {

        if ($user && $user->qr_image && !$path && !$scene) {
            return [
                'code' => 0,
                'data' => $user->qr_image,
            ];
        }

        $appid = Env::get('wx.appid');
        $appsecret = Env::get('wx.appsecret');
        $token = get_wx_token($appid, $appsecret);

        if (is_array($token)) {
            return $token;
            // return [
            //     'code' => 1,
            //     'msg' => $token->errMsg,
            // ];
        }
        $api = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$token}";
        $data = json_encode([
            'scene' => $scene ? $scene : $user->id,
            'page' => $path ? trim($path, '/') : 'pages/index/index',
            'width' => 246,
            'check_path' => false,
            // 'env_version'=>'trial'
        ]);
        $http = new Http;
        $response = $http->post($api, $data);
        $json_response = json_decode($response, true);
        if (!is_array($json_response)) {
            $file = self::saveTempImageByContent($response);
            if (!file_exists($file)) {
                return [
                    'code' => 1,
                    'msg' => '二维码保存失败',
                ];
            }
            //返回图片
            if (!$path) {
                $user->qr_image =  '/' . $file;
                $user->save();
                return [
                    'code' => 0,
                    'data' => $user->qr_image,
                ];
            } else {
                return [
                    'code' => 0,
                    'data' =>  '/' . $file,
                ];
            }
        } else {
            Log::write('二维码生成失败:' . json_encode($json_response), 'error');
            //返回文字
            // $res = json_decode($response, true);
            return [
                'code' => 1,
                'msg' => $json_response['errmsg'],
            ];
        }
    }

    static function saveTempImageByContent($content)
    {
        $dir1 = ROOT_PATH . 'public/uploads/wx_qrcode/';
        if (!is_dir($dir1)) @mkdir($dir1, 0700);
        $save_name = md5(base64_encode($content)) . '.jpg';
        $save_path = 'uploads/wx_qrcode/' . $save_name;
        $fp = fopen($dir1 . $save_name, 'w');
        fwrite($fp, $content);
        fclose($fp);
        return $save_path;
    }
}
